package com.example.easycharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.Configuration;
import com.example.easycharge.repository.ConfRepository;
import com.example.easycharge.service.ConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("conf")
public class ConfController {
    @Autowired
    private ConfService confService;
    @Autowired
    private ConfRepository confRepository;

    @GetMapping("")
    public JSONObject getAllConf() {
        JSONObject result = new JSONObject();
        result.put("content",confRepository.findAll());
        return result;
    }

    @GetMapping("/now")
    public JSONObject getNowConf() {
        JSONObject result = new JSONObject();
        result.put("content", confService.getNowConf());
        return result;
    }

    @PostMapping("")
    public JSONObject addNewConf(@RequestBody Configuration configuration) {
        JSONObject result = new JSONObject();
        result.put("detail", confRepository.save(configuration));
        result.put("message", "新增配置成功");
        return result;
    }

    @PutMapping("{confId}")
    public JSONObject setConf(@PathVariable("confId") long confId) {
        JSONObject result = new JSONObject();
        if (confRepository.countByConfigurationID(confId) == 0) {
            result.put("message", "此配置不存在");
            // TODO: 2022-05-09 随手写的故障码 
            result.put("errorCode", 40011);
            return result;
        }
        Configuration configuration = confRepository.getById(confId);
        confService.setNewConf(configuration);
        result.put("message", "设置成功");
        return result;
    }

    @DeleteMapping("{confId}")
    public JSONObject deleteConf(@PathVariable("confId") long confId) {
        confRepository.deleteById(confId);
        JSONObject result = new JSONObject();
        result.put("message", "删除成功");
        return result;
    }

}
